package com.xinyu.controller;


import com.xinyu.domain.Post;
import com.xinyu.domain.Reply;
import com.xinyu.service.IPostService;
import com.xinyu.service.IReplyService;
import com.xinyu.utils.JWTUtils;
import com.xinyu.vo.BaseResult;
import com.xinyu.vo.PostRequest;
import com.xinyu.vo.ReplyRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  跟帖
 * </p>
 *
 * @author: XinYu
 * @since 2025-02-17
 */
@RestController
@RequestMapping("/reply")
public class ReplyController {
    @Autowired
    private IReplyService replyService;

    @Autowired
    private IPostService postService;

    @Autowired
    private HttpServletRequest request;

    @PostMapping("/queryByCondition")
    public ResponseEntity<BaseResult> queryByCondition(@RequestBody ReplyRequest replyRequest){
        BaseResult br = replyService.queryByPage(replyRequest);
        return ResponseEntity.ok(br);
    }


    @PutMapping("/update")
    public ResponseEntity<BaseResult> modify(@RequestBody Reply reply){
        replyService.updateById(reply);
        return ResponseEntity.ok(BaseResult.ok());
    }

    @PostMapping("/save")
    public ResponseEntity<BaseResult> add(@RequestBody Reply reply){
        // 1 当前登录用户的id
        String token = request.getHeader("Authorization");
        reply.setUserId(JWTUtils.getUserIdFromToken(token));

        //2 设置发布时间-当前系统时间
        LocalDateTime now = LocalDateTime.now();
        // 格式化时间（可选）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        reply.setPublishTime(formattedDateTime);

        replyService.save(reply);

        Post post = postService.getById(reply.getPostId());
        post.setReplyCount(post.getReplyCount()+1);
        post.setLastReplyTime(formattedDateTime);
        postService.updateById(post);

        return ResponseEntity.ok(BaseResult.ok());
    }




}

